package com.lk.servlet;

import com.lk.bean.Goods;

import javax.servlet.ServletConfig;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.BufferedReader;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.*;

/**
 * @author lk
 * @date 2020/4/14 0014 11:33
 * @description:
 */
public class DoGoodsServlet extends HttpServlet {
    // 获取所有的商品
    public static List<Goods> getAllGoods(String filePath) {
        ArrayList<Goods> goodsList = new ArrayList<>();
        try {
            BufferedReader stream1 = new BufferedReader(
                    new InputStreamReader(
                            new FileInputStream(filePath), "UTF-8"));
            String line = null;
            ArrayList<String> list = new ArrayList<>();
            while ((line = stream1.readLine()) != null) {
                list.add(line);
            }
            for (String s : list) {
                String[] str = s.split("，");
                Goods goods = new Goods(str[0], str[1], str[2], str[3], str[4]);
                goodsList.add(goods);
            }
            stream1.close();
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            return goodsList;
        }
    }


    @Override
    public void init(ServletConfig config) throws ServletException {
        super.init(config);
        List<Goods> goodsList = getAllGoods(this.getServletContext().getRealPath("goods/goods.txt"));
        HashMap<Goods, Integer> map = new HashMap<Goods, Integer>();
        for (Goods goods : goodsList) {
            map.put(goods, 0);
        }
        this.getServletContext().setAttribute("allGoods", map);
    }

    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        doPost(req, resp);
    }

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        req.setCharacterEncoding("UTF-8");
        resp.setCharacterEncoding("UTF-8");
        resp.setContentType("text/html; charset=UTF-8");
        HashMap<Goods, Integer> goodsMap = (HashMap<Goods, Integer>) req.getServletContext().getAttribute("allGoods");
        String goodsType = req.getParameter("goodsType");
        Map<Goods, Integer> map = new HashMap<Goods, Integer>();
        for (Goods goods1 : goodsMap.keySet()) {
            if (goods1.getGoodsType().equals(goodsType)) {
                map.put(goods1,goodsMap.get(goods1));
            }
        }

        req.setAttribute("goodsMap", map);
        req.getRequestDispatcher("goods.jsp").forward(req, resp);
    }

}
